package al2addTwoNumbers;


import java.util.List;

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

public class AddTwoNumbers2 {

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode list = new ListNode(0);
        ListNode cur = list;
        int carry = 0;
        while (l1!=null || l2!=null || carry!=0){
            int sum = carry;

            if (l1!=null) {
                sum+= l1.val;
                l1 = l1.next;
            }

            if (l2!=null) {
                sum+= l2.val;
                l2 = l2.next;
            }

            carry = sum/10;
            cur.next = new ListNode(sum%10);
            cur = cur.next;
        }

        return list.next;
    }


    public static void printList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
        System.out.println();
    }

    // 主方法用于测试
    public static void main(String[] args) {
        // 创建两个有序链表
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);
/*
        l1.next.next.next = new ListNode(9);
*/

        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);
/*        l2.next.next.next = new ListNode(8);
        l2.next.next.next.next = new ListNode(9);*/
/*      l2.next.next.next.next.next = new ListNode(11);*/
        // 打印原链表
        System.out.println("List 1:");
        printList(l1);

        System.out.println("List 2:");
        printList(l2);

        // 合并两个链表
        ListNode mergedList = addTwoNumbers(l1, l2);

        // 打印合并后的链表
        System.out.println("Merged List:");
        printList(mergedList);
    }
}
